BootApplication
//Servizio per la gestione delle NOTOIFICHE
.service("MonitoraggioTplSrv",['configuration'
                               ,"$rootScope"
                              ,'$q'
                              ,'$translate'
                              ,"$filter"
                              ,"$http"
                              ,"$timeout"
                              ,"$mdToast"
                              ,"log"
                              ,"olFormatService"
                              ,"olLayerService"
                              ,"olStyleService"
                              ,"DateService"
                              ,"readerMenu"
                , function(configuration
                		  ,$rootScope
                          ,$q
                          ,$translate
                          ,$filter
                          ,$http
                          ,$timeout
                          ,$mdToast
                          ,log
                          ,olFormatService
                          ,olLayerService
                          ,olStyleService
                          ,DateService
                          ,readerMenu
) {
     MonitoraggioTplSrv = this;
     $rootScope.corseAttive = $rootScope.corseAttive ? $rootScope.corseAttive : []; 
     
     MonitoraggioTplSrv.olMap = null;
     
     MonitoraggioTplSrv.elementsAgency = [];
     MonitoraggioTplSrv.elementsRoute  = [];
     MonitoraggioTplSrv.vector         = null;
     MonitoraggioTplSrv.vectorStopLine = new ol.source.Vector();
     MonitoraggioTplSrv.layerStopLine  = new ol.layer.Vector({source: MonitoraggioTplSrv.vectorStopLine
 	                                                         ,name  : configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_STOP"]    
 	                                                         });
     MonitoraggioTplSrv.zoomLevel            = configuration.getParam("Constants").ZOOM_MAP;
     MonitoraggioTplSrv.showAddLineStopArray = [];
     MonitoraggioTplSrv.arrayStop            = [];
     MonitoraggioTplSrv.arrayLine            = [];
     MonitoraggioTplSrv.trackings            = [];
     MonitoraggioTplSrv.listaEventi          = [];
     MonitoraggioTplSrv.listaAllarmi         = [];

     var _layerMezzo = configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_MAPPA"];
     var _imageMezzo = olStyleService.createOlStyleIcon( configuration.getParam("Constants").ContextPath 
                                                       + configuration.getParam("Constants").iconStyles[_layerMezzo]
                                                       ,[31, 46]
                                                       ,1
                                                       ,[0, 0]
                                                       );

     var _styleMezzoCache = [];
     
     var _getColorRoute = function(_properties){
    	 _backgroundColor = _properties.color     ? _properties.color     : "#005E91";
		 _textColor       = _properties.textColor ? _properties.textColor : "#FFF";

		 if(_backgroundColor.indexOf('#') != 0)
			 _backgroundColor = '#' + _backgroundColor;
		 
		 if(_properties.color && !_properties.textColor)
			 _textColor = inverseColor(_backgroundColor);

		 _strokeColor = _textColor;
		 
		 if(_textColor.indexOf('#') != 0)
			 _textColor = '#' + _textColor;
		 if(_strokeColor.indexOf('#') != 0)
			 _strokeColor = '#' + _strokeColor;
		 
		 return {backgroundColor: _backgroundColor
			    ,textColor      : _textColor      
			    ,strokeColor    : _strokeColor    
		        };
     };
     
     
     var _styleMezzo = function(_properties){
    	 _agencyId        = _properties.agencyId;
    	 _routeId         = _properties.routeId;
    	 _key             = _agencyId + "@" + _routeId;
    	 if(!_styleMezzoCache[_key]){
    		 _color = _getColorRoute(_properties);
    		 _styleMezzoCache[_key] = new ol.style.Style({image: new ol.style.Circle({radius: 5 
                                                                                    ,fill   : new ol.style.Fill  ({color:  _color.backgroundColor})
                                                                                    ,stroke : new ol.style.Stroke({color : _color.strokeColor
                   	                                                                                              ,width : 1
                   	                                                                                              })
                                                                                    }) 
                                                        ,zIndex: 20
                                                        });
    	 }
    	 return _styleMezzoCache[_key];
     };
     
     var _styleMezzoOverlayCache = [];
     
     var inverseColor = function(_color){
    	 if(_color.length == 7 
    	 || _color.length == 4
    	 ){
    		if(_color.length == 7){
    		 _r = parseInt(_color.substring(1,3), 16);
    		 _g = parseInt(_color.substring(3,5), 16);
    		 _b = parseInt(_color.substring(5  ), 16);
    		}else if(_color.length == 4){
    		 _r = parseInt(_color.substring(1,2), 16);
    		 _g = parseInt(_color.substring(2,3), 16);
    		 _b = parseInt(_color.substring(3  ), 16);
    		}
    		_r = (255 - _r).toString(16);
    		_g = (255 - _g).toString(16);
    		_b = (255 - _b).toString(16);
    		_r = (_r.length == 1 ? "0" : "") + _r;
    		_g = (_g.length == 1 ? "0" : "") + _g;
    		_b = (_b.length == 1 ? "0" : "") + _b;
    		return "#" + _r + _g +_b;
    	 } 
    	 return '#000';
     };
     MonitoraggioTplSrv.inverseColor = function(_color){
    	return inverseColor(_color);  
     }
     MonitoraggioTplSrv.styleMezzo = function(_properties){
    	 return _styleMezzo(_properties);
     }
     MonitoraggioTplSrv.styleMezzoOverlay = function(_properties){
    	 _agencyId        = _properties.agencyId;
    	 _routeId         = _properties.routeId;
    	 _key             = _agencyId + "@" + _routeId;
    	 if(!_styleMezzoOverlayCache[_key]){
    		 //_text  = _routeId
    		 _text = '';
    		 _color = _getColorRoute(_properties);

    		 _styleMezzoOverlayCache[_key] = new ol.style.Style({image: new ol.style.Circle({radius: 15
                                                                                    ,fill  : new ol.style.Fill  ({color:  _color.backgroundColor})
                                                                                    ,stroke: new ol.style.Stroke({color : _color.strokeColor
                   	                                                                                             ,width : 3
                   	                                                                                             })
                                                                                    }) 
                                                        ,zIndex: 21
                                                        ,text: new ol.style.Text({text   : _text
                                                                                 ,fill   : new ol.style.Fill({color: _color.textColor})
                                                                                 ,font   : 'bold italic 0.8em Arial, Verdana, Helvetica, sans-serif'
                                                                                 ,offsetY: 0
                                                                                })
                                                        });
    	 }
    	 return _styleMezzoOverlayCache[_key];
     };     
     
     var _stylePercorso = function(feature){
    	 _color = 'rgba(0, 94, 145, 0.7)';
			if(feature 
			&& feature.getProperties()
			&& feature.getProperties().routeColor
			){
				_color = feature.getProperties().routeColor;
				if(_color.indexOf('#') != 0)
					_color = '#' + _color;
			}
    	 return new ol.style.Style({stroke: new ol.style.Stroke({color: _color
                                                                ,width: 3
                                                                })
                                  ,zIndex: 2
                                  });
    };


     
     
   var _styleStop = new ol.style.Style({image: new ol.style.Circle({radius : 4 
                                                                   ,fill   : new ol.style.Fill  ({color:  '#962D00'/*'#f00'*/})
                                                                   ,stroke : new ol.style.Stroke({color : '#fff'/*'#000'*/
                                                                                                 ,width : 1
                                                                                                 })
                                                                   }) 
                                       ,zIndex: 3
                                     });
   
   this.styleStop = function(){
	   return _styleStop;
   }
   
//Function per centrare mappa chiamata da sinottico   
   this.centraMappa = function(_lon, _lat){
	   log.debug("Centa in " + _lon + ", " + _lat);
	   if(MonitoraggioTplSrv.olMap){
		   _extent = olFormatService.olProjTransorm(_lon
				                                   ,_lat
				                                   ,configuration.getParam("Constants").SOURCE_PROJECTION
				                                   ,configuration.getParam("Constants").DEST_PROJECTION
                                                   );
		   MonitoraggioTplSrv.olMap.getView().setCenter(_extent);
		   MonitoraggioTplSrv.olMap.getView().setZoom  (MonitoraggioTplSrv.zoomLevel);
	   }
   }
   
   this.initLayerMezzi = function(_olMap){
	   if(MonitoraggioTplSrv.olMap == null){
           MonitoraggioTplSrv.olMap = _olMap;
           MonitoraggioTplSrv.olMap.addLayer(MonitoraggioTplSrv.layerStopLine);
       }
	    if(MonitoraggioTplSrv.vector == null){
	    	_vectorSource = new ol.source.Vector();
	    	_layer = new ol.layer.Vector({source: _vectorSource
                                         ,name  : _layerMezzo    
                                         });
	    	MonitoraggioTplSrv.vector = _vectorSource;
            MonitoraggioTplSrv.olMap.addLayer(_layer);
	    }
	};
     this.getKey = function(_element){
         _key = _element.agencyId;
         if(_element.routeId)
             _key += "#@#" + _element.routeId;
         if(_element.tripId)
             _key += "#@#" + _element.tripId;
         if(_element.startDay)
             _key += "#@#" + _element.startDay;
         return _key;
     };
//FUNCTION PER AGGIUNGERE PERCORSI E FERMATE
    this.addTrip = function(_element, _olMap){
        if(MonitoraggioTplSrv.olMap == null){
            MonitoraggioTplSrv.olMap = _olMap;
            MonitoraggioTplSrv.olMap.addLayer(MonitoraggioTplSrv.layerStopLine);
        }
        
        this.addNewLineStop(_element.agencyId);
        
        this.monitoraggio(_element);
        if(!_element.tripId && !_element.routeId)
            MonitoraggioTplSrv.elementsAgency.push(_element);
        else if(!_element.tripId)
            MonitoraggioTplSrv.elementsRoute.push(_element);
        
        
    };
    MonitoraggioTplSrv.tripToRemove = [];
    //Remove Trip
    this.removeTrip = function(_element, _olMap){
    	if(MonitoraggioTplSrv.olMap == null){
            MonitoraggioTplSrv.olMap = _olMap;
        }
    	if(!MonitoraggioTplSrv.tripToRemove[_element.agencyId]){
    		MonitoraggioTplSrv.tripToRemove[_element.agencyId] = [];
    	}
    	MonitoraggioTplSrv.tripToRemove[_element.agencyId].push(_element.tripId);
    	
    };
    //Restore Trip
    this.restoreTrip = function(_element, _olMap){
    	if(!MonitoraggioTplSrv.tripToRemove[_element.agencyId]){
    		MonitoraggioTplSrv.tripToRemove[_element.agencyId] = [];
    	}else{
    		_agencyArray = MonitoraggioTplSrv.tripToRemove[_element.agencyId];
    		_nuovoArray  = [];
    		for(_key in _agencyArray){
    			_tripIdIter = _agencyArray[_key];
    			if(_tripIdIter != _element.tripId)
    				_nuovoArray.push(_tripIdIter);	
    		}
    		MonitoraggioTplSrv.tripToRemove[_element.agencyId] = _nuovoArray;
    	}
    };
    this.isTripVisualizzato = function(_element, _olMap){
    	if(MonitoraggioTplSrv.vector){
    		_features = MonitoraggioTplSrv.vector.getFeatures();
    		for(_idx in _features){
    			_properties = _features[_idx].getProperties();
    			if(_properties.agencyId == _element.agencyId
    			&& _properties.tripId   == _element.tripId
    			)
    				return true;
    		}
    		
    	}
    	return false;
    };
    
    this.addNewLineStop = function(_idAgency, _idRoute, _idTrip, _startDay){
        var _defer = $q.defer();
        
        _element = {agencyId: _idAgency
                   ,routeId : _idRoute
                   ,tripId  : _idTrip
                   ,startDay: _startDay
                   };
        
        _promisePercorsi = this.loadPercorsi(_element);
        _promiseFermate  = this.loadFermate (_element);
        
//        MonitoraggioTplSrv.layersStop     = [];
//        MonitoraggioTplSrv.layersLine     = [];
        
        _layerNameStop     = configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_STOP"];
        _layerNamePercorso = configuration.getParam("Constants").MONITORAGGIO_TPL_MMONITORAGGIO_PERCORSO;
        
        this.addLayer(_promisePercorsi, _stylePercorso                           , _defer, _layerNamePercorso, _element, false, true );
        this.addLayer(_promiseFermate , function(_resolution){return _styleStop;}, _defer, _layerNameStop    , _element, true , false);
    };
    
    this.centraFermata = function(agencyId, tripId, stopId){
    	log.debug("centraFermata " + agencyId + ", " + tripId + ", " + stopId);
    	if(MonitoraggioTplSrv.arrayStop){
    		log.debug("Defined arrayStop");
    		_tripAgency = MonitoraggioTplSrv.arrayStop[agencyId];
    		if(_tripAgency){
    			log.debug("Defined _tripAgency by agency");
    			_stops = _tripAgency[tripId];
    			if(_stops){
    				log.debug("Defined stops");
    				for(_stopIdx in _stops){
	    				_stop = _stops[_stopIdx];
	    				if(_stop.getProperties().stopId == stopId){
	    					log.debug("Trovata stop");
		    				MonitoraggioTplSrv.olMap.getView().fit(_stop.getGeometry().getExtent()
		    						                              ,MonitoraggioTplSrv.zoomLevel
		    						                              );
	    				}
    				}	
    			}
    		}
    	}  	
    }
    /*
    this.showAddLineStop = function(_idAgency, _idRoute, _idTrip, _startDay){
    	return MonitoraggioTplSrv.showAddLineStopArray[_idAgency + "@" + _idTrip];
    }
    this.addLineStop = function(_idAgency, _idRoute, _idTrip, _startDay){
    	if(MonitoraggioTplSrv.arrayLine[_idAgency]){
    		_agencyArray = MonitoraggioTplSrv.arrayLine[_idAgency];
    		if(_agencyArray[_idTrip]){
    			_array = _agencyArray[_idTrip];
    			for(_idx = 0 ; _idx < _array.length ; _idx++){
    				MonitoraggioTplSrv.vectorStopLine.addFeature(_array[_idx]);
    			}
    		}
    	}

    	if(MonitoraggioTplSrv.arrayStop[_idAgency]){
    		_agencyArray = MonitoraggioTplSrv.arrayStop[_idAgency];
    		if(_agencyArray[_idTrip]){
    			_array = _agencyArray[_idTrip];
    			for(_idx = 0 ; _idx < _array.length ; _idx++){
    				MonitoraggioTplSrv.vectorStopLine.addFeature(_array[_idx]);
    			}
    		}
    	}
    	MonitoraggioTplSrv.showAddLineStopArray[_idAgency + "@" + _idTrip] = false;
    };

    this.removeLineStop = function(_idAgency, _idRoute, _idTrip, _startDay, _olMap, _properties){
    	
    	if(MonitoraggioTplSrv.arrayLine[_idAgency]){
    		_agencyArray = MonitoraggioTplSrv.arrayLine[_idAgency];
    		if(_agencyArray[_idTrip]){
    			_array = _agencyArray[_idTrip];
    			for(_idx = 0 ; _idx < _array.length ; _idx++){
    				MonitoraggioTplSrv.vectorStopLine.removeFeature(_array[_idx]);
    			}
    		}
    	}

    	if(MonitoraggioTplSrv.arrayStop[_idAgency]){
    		_agencyArray = MonitoraggioTplSrv.arrayStop[_idAgency];
    		if(_agencyArray[_idTrip]){
    			_array = _agencyArray[_idTrip];
    			for(_idx = 0 ; _idx < _array.length ; _idx++){
    				MonitoraggioTplSrv.vectorStopLine.removeFeature(_array[_idx]);
    			}
    		}
    	}
    	MonitoraggioTplSrv.showAddLineStopArray[_idAgency + "@" + _idTrip] = true;
    };
    */
    this.addLayer = function(_promise, _functionStyle, _defer, _layerName, _element, _isStop, _isShape, _isEvent, _isAnomalia, _isAllarme){
        _promise.then(function(response) {
                if(response.status = 200)
                    if(response.data.success){
                        
                        _features     =  olFormatService.olReadFeaturesToGeoJson(response.data.aaData
                                                                                ,MonitoraggioTplSrv.olMap.getOptions().getSourceProjection()
                                                                                ,MonitoraggioTplSrv.olMap.getOptions().getDestProjection  ()
                                                                                );
                        if(_isStop){
                        	
                        	/** Se il layer e' una FERMATA **/
                            for(idx = 0 ; idx < _features.length ; idx++){
                            	_features[idx].setStyle(_functionStyle);
                            }
                            MonitoraggioTplSrv.vectorStopLine.addFeatures(_features);
                            for(_idx in _features){
                            	_agencyId = _features[_idx].getProperties().agencyId;
                            	_tripIds  = _features[_idx].getProperties().tripIds;
                            	if(!MonitoraggioTplSrv.arrayStop[_agencyId]){
                            		MonitoraggioTplSrv.arrayStop[_agencyId] = [];
                            	}
                            	_agencyArray = MonitoraggioTplSrv.arrayStop[_agencyId];
                            	for(_keyTripIds in _tripIds){
                            		_tripId = _tripIds[_keyTripIds];
	                            	if(!_agencyArray[_tripId]){
	                            		_agencyArray[_tripId] = [];
	                            	}
	                            	_agencyArray[_tripId].push(_features[_idx]);
                            	}
                            }
                        }else if(_isShape){
                        	
                        	/** Se il layer e' un PERCORSO **/
                            for(idx = 0 ; idx < _features.length ; idx++){
                            	_features[idx].setStyle(_functionStyle(_features[idx]));
                            }
                            //MonitoraggioTplSrv.vectorStopLine.addFeatures(_features);
                            for(_idx in _features){
                            	_feature = _features[_idx];
                            	_shapeId = _feature.getProperties().shapeId;
                           		MonitoraggioTplSrv.arrayLine[_shapeId] = _feature;
                            }
                        } else if (_isEvent) {
                        	log.debug("MonitoraggioTplService >>> La feature da aggiungere e' un EVENTO");
                        	_features     =  olFormatService.olReadFeaturesToGeoJson(response.data.aaData.data[0]
                                    				,MonitoraggioTplSrv.olMap.getOptions().getSourceProjection()
                                    				,MonitoraggioTplSrv.olMap.getOptions().getDestProjection  ());
                        	/** Se il layer e' un EVENTO **/
                        	if(MonitoraggioTplSrv.vectorEventi == null){
                        		_vectorSource = new ol.source.Vector();
                        		_layer = new ol.layer.Vector({source: _vectorSource
   		                                                     ,style : _functionStyle
   		                                                     ,name  : _layerName    
   	                                                         });
                        		MonitoraggioTplSrv.vectorEventi = _vectorSource;
                        		/** add layer alla mappa **/
                                MonitoraggioTplSrv.olMap.addLayer(_layer);
                        	}
                    		_featureToAdd    = [];
                    		_fetauresLength = _features.length;
                    		/** Ciclo tutte le feature degli eventi **/
                    		for(idx = 0 ; idx <  _fetauresLength ; idx++){
                    			_featureElement = _features[idx];
                    			if( _featureElement.getProperties().codiceEvento == _element.codiceEvento){
                					_featureToAdd.push(_featureElement);
                					MonitoraggioTplSrv.eventFeatureView[_element.codiceEvento] =_featureElement;
                					if (MonitoraggioTplSrv.eventFeatureHide[_element.codiceEvento]!=undefined)
                						delete MonitoraggioTplSrv.eventFeatureHide[_element.codiceEvento];
                					break;
                    			}
                    		}
                    		for(_key in _featureToAdd){
                    			MonitoraggioTplSrv.vectorEventi.addFeature(_featureToAdd[_key]);
                    		}
                        }  else if (_isAnomalia) {
                        	log.debug("MonitoraggioTplService >>> La feature da aggiungere e' un ANOMALIA");
                        	_features     =  olFormatService.olReadFeaturesToGeoJson(response.data.aaData.data[0]
						            				,MonitoraggioTplSrv.olMap.getOptions().getSourceProjection()
						            				,MonitoraggioTplSrv.olMap.getOptions().getDestProjection  ());
                        	/** Se il layer e' un ANOMALIA **/
                        	if(MonitoraggioTplSrv.vectorAnomalie == null){
                        		_vectorSource = new ol.source.Vector();
                        		_layer = new ol.layer.Vector({source: _vectorSource
   		                                                     ,style : _functionStyle
   		                                                     ,name  : _layerName    
   	                                                         });
                        		MonitoraggioTplSrv.vectorAnomalie = _vectorSource;
                        		/** add layer alla mappa **/
                                MonitoraggioTplSrv.olMap.addLayer(_layer);
                        	}
                    		_featureToAdd    = [];
                    		_fetauresLength = _features.length;
                    		/** Ciclo tutte le feature degli anomalie **/
                    		for(idx = 0 ; idx <  _fetauresLength ; idx++){
                    			_featureElement = _features[idx];
                    			if( _featureElement.getProperties().codiceAnomalia == _element.codiceAnomalia){
                					_featureToAdd.push(_featureElement);
                					MonitoraggioTplSrv.anomaliaFeatureView[_element.codiceAnomalia] =_featureElement;
                					if (MonitoraggioTplSrv.anomaliaFeatureHide[_element.codiceAnomalia]!=undefined)
                						delete MonitoraggioTplSrv.anomaliaFeatureHide[_element.codiceAnomalia];
                					break;
                    			}
                    		}
                    		for(_key in _featureToAdd){
                    			MonitoraggioTplSrv.vectorAnomalie.addFeature(_featureToAdd[_key]);
                    		}
                        }  else if (_isAllarme) {
                        	log.debug("MonitoraggioTplService >>> La feature da aggiungere e' un ALLARME");
                        	_features     =  olFormatService.olReadFeaturesToGeoJson(response.data.aaData
						            				,MonitoraggioTplSrv.olMap.getOptions().getSourceProjection()
						            				,MonitoraggioTplSrv.olMap.getOptions().getDestProjection  ());
                        	/** Se il layer e' un ALLARME **/
                        	if(MonitoraggioTplSrv.vectorAllarme == null){
                        		_vectorSource = new ol.source.Vector();
                        		_layer = new ol.layer.Vector({source: _vectorSource
   		                                                     ,style : _functionStyle
   		                                                     ,name  : _layerName    
   	                                                         });
                        		MonitoraggioTplSrv.vectorAllarme = _vectorSource;
                        		/** add layer alla mappa **/
                                MonitoraggioTplSrv.olMap.addLayer(_layer);
                        	}
                    		_featureToAdd    = [];
                    		_fetauresLength = _features.length;
                    		/** Ciclo tutte le feature degli anomalie **/
                    		for(idx = 0 ; idx <  _fetauresLength ; idx++){
                    			_featureElement = _features[idx];
                    			if( _featureElement.getProperties().codiceAllarme == _element.codiceAllarme){
                					_featureToAdd.push(_featureElement);
                					MonitoraggioTplSrv.allarmeFeatureView[_element.codiceAllarme] =_featureElement;
                					if (MonitoraggioTplSrv.allarmeFeatureHide[_element.codiceAllarme]!=undefined)
                						delete MonitoraggioTplSrv.allarmeFeatureHide[_element.codiceAllarme];
                					break;
                    			}
                    		}
                    		for(_key in _featureToAdd){
                    			MonitoraggioTplSrv.vectorAllarme.addFeature(_featureToAdd[_key]);
                    		}
                        }else if(_element){
                        	_featureToDelete = [];
                        	_featureToAdd    = [];
                        	_fetaureMapLength = MonitoraggioTplSrv.vector.getFeatures().length;
                        	if(_fetaureMapLength == 0)
                        		_featureToAdd = _features;
                        	for(idx = 0 ; idx <  _fetaureMapLength ; idx++){
                        		_trovato           = false;
                        		_featureMapElement = MonitoraggioTplSrv.vector.getFeatures()[idx];
                        		_idxListaAttuale   = 0;
                        		_daElaborare       = false;
                        		if(_element.tripId
                                && _element.tripId   == _featureMapElement.getProperties().tripId
                                && _element.agencyId == _featureMapElement.getProperties().agencyId
                                ){
                        			_daElaborare = true;
                        		}else if(_element.routeId
                        		      && _element.routeId  == _featureMapElement.getProperties().routeId
                        		      && _element.agencyId == _featureMapElement.getProperties().agencyId
                        		){
                        			_daElaborare = true;
                        		}else if(_element.agencyId == _featureMapElement.getProperties().agencyId){
                        			_daElaborare = true;
                        		}else{
                        			_daElaborare = false;
                        		}
                        		if(_daElaborare){
	                        		while(_trovato == false
	                        		&&    _idxListaAttuale < _features.length
	                        		){
	                        			if(_features[_idxListaAttuale].getProperties().id == _featureMapElement.getProperties().id){
	                        				_featureMapElement.getGeometry().setCoordinates(_features[_idxListaAttuale].getGeometry().getCoordinates());
	                        				_featureMapElement.setProperties (_features[_idxListaAttuale].getProperties());
	                        				_trovato = true;
	                        			}
	                        			_idxListaAttuale++;
	                        		}
	                        		if(!_trovato)
	                        			_featureToDelete.push(_featureMapElement);
                        		}
                        	}
                        	
                        	for(_key in _featureToDelete){
                        		_feature = _featureToDelete[_key];
                        		delete $rootScope.corseAttive[_feature.getProperties().id];
                        		MonitoraggioTplSrv.vector.removeFeature(_feature);
                        	}
                        	if(_featureToAdd.length == 0){
                        		_fetauresLength = _features.length;
	                        	for(idx = 0 ; idx <  _fetauresLength ; idx++){
	                        		_trovato        = false;
	                        		_featureElement = _features[idx];
	                        		_idxLista       = 0;
	                        		while(_trovato == false
	                        		&&    _idxLista < MonitoraggioTplSrv.vector.getFeatures().length
	                        		){
	                        			if(MonitoraggioTplSrv.vector.getFeatures()[_idxLista].getProperties().id == _featureElement.getProperties().id){
	                        				_trovato = true;
	                        			}
	                        			_idxLista++;
	                        		}
	                        		if(!_trovato)
	                        			_featureToAdd.push(_featureElement);
	                        	}
                        	}
                        	for(_key in _featureToAdd){
                        		_feature = _featureToAdd[_key];
                        		_feature.setStyle(_functionStyle(_feature.getProperties()));
                        		$rootScope.corseAttive[_feature.getProperties().id] = true;
                        		MonitoraggioTplSrv.vector.addFeature(_feature);
                        	}
                        }
                        
                    }
           _defer.resolve(1);
                                         }
                    ,function(response) {
                                         _defer.reject({ msg : ""});
                                         _defer.resolve(0);
                                        }
                      );//Then
    };//addLayer 
    this.currentLine = null;
    this.showLine = function(_shapeId){
    	this.removeLine();
    	this.currentLine = MonitoraggioTplSrv.arrayLine[_shapeId];
    	MonitoraggioTplSrv.vectorStopLine.addFeature(this.currentLine);
	};
	this.removeLine = function(){
		if(this.currentLine != null){
			MonitoraggioTplSrv.vectorStopLine.removeFeature(this.currentLine);
			this.currentLine = null;
		}
	}
    
    
    //Function per add feature agency    
    this.loadPercorsi = function(_element){
           var _defer = $q.defer();
           var req = {method: 'POST'
                     ,url   : configuration.getParam("Constants").URL_RICERCA_MONITORAGGIO_FEATURE_PERCORSI
                     ,params: {agencyId: (_element.agencyId ? _element.agencyId : "")
                              ,routeId : (_element.routeId  ? _element.routeId  : "")
                              ,tripId  : (_element.tripId   ? _element.tripId   : "")
                              ,startDay: (_element.startDay ? _element.startDay : 0)
                              }
                     };
           $http(req).then(function(response     ){_defer.resolve(response);}
                          ,function(errorResponse){_defer.resolve(null);}
                          );
           
           return _defer.promise;
       };
     //Function per add feature agency    
     this.loadFermate = function(_element){
       var _defer = $q.defer();
       var req = {method: 'POST'
                 ,url   : configuration.getParam("Constants").URL_RICERCA_MONITORAGGIO_FEATURE_FERMATE
                 ,params: {agencyId: (_element.agencyId ? _element.agencyId : "")
                          ,routeId : (_element.routeId  ? _element.routeId  : "")
                          ,tripId  : (_element.tripId   ? _element.tripId   : "")
                          ,startDay: (_element.startDay ? _element.startDay : 0)
                          }
                 };
       $http(req).then(function(response     ){_defer.resolve(response);}
                      ,function(errorResponse){_defer.resolve(null);}
                      );
       
       return _defer.promise;
     };
     
     this.refreshMonitoraggio = function(_element){
    	 /*
         _oldLayer = MonitoraggioTplSrv.layer[MonitoraggioTplSrv.getKey(_element)];
         if(_oldLayer)
             MonitoraggioTplSrv.olMap.removeLayer(_oldLayer);
    	  */
         var _defer = $q.defer();
         _promise = this.monitora(_element);
         this.addLayer(_promise, _styleMezzo, _defer, _layerMezzo, _element);
     }
     
     this.monitoraggio = function(_element){
         _trovatoPadre = false;
         if(_element.tripId){
             for(_key in MonitoraggioTplSrv.elementsAgency){
                 if(_element.agencyId == MonitoraggioTplSrv.elementsAgency[_key].agencyId){
                     _trovatoPadre = true;
                 }
             }
             if(_trovatoPadre == false){
                 for(_key in MonitoraggioTplSrv.elementsRoute){
                     if(_element.agencyId == MonitoraggioTplSrv.elementsAgency[_key].agencyId
                     && _element.routeId  == MonitoraggioTplSrv.elementsAgency[_key].routeId
                     ){
                         _trovatoPadre = true;
                     }
                 }
              }
         }else if(_element.routeId){
             
             for(_key in MonitoraggioTplSrv.elementsAgency){
                 if(_element.agencyId == MonitoraggioTplSrv.elementsAgency[_key].agencyId){
                     _trovatoPadre = true;
                 }
             }
         }
         if(_trovatoPadre){
             /*
             _key          = MonitoraggioTplSrv.getKey(_element);
            _oldLayerStop = MonitoraggioTplSrv.layersStop[_key];
            _oldLayerLine = MonitoraggioTplSrv.layersLine[_key];
            
            if(_oldLayerStop)
                MonitoraggioTplSrv.olMap.removeLayer(_oldLayerStop);
            if(_oldLayerLine)
                MonitoraggioTplSrv.olMap.removeLayer(_oldLayerLine);
                */
             return;
         }
         
         this.refreshMonitoraggio(_element);
         $timeout(function() {MonitoraggioTplSrv.monitoraggio(_element);}
                 ,5000
                 );
         
         
     };
     
    //Function per add feature agency    
     this.monitora = function(_element){
         
        if(this.olMap
        && this.olMap.getView()
        && this.olMap.getSize()
        ){
               _extent = ol.proj.transformExtent(this.olMap.getView().calculateExtent(this.olMap.getSize())
                                                  ,configuration.getParam("Constants").DEST_PROJECTION
                                                  ,configuration.getParam("Constants").SOURCE_PROJECTION
                                                  );
            if(_extent != null
            && _extent.length == 4
            && isNaN(_extent[0]) == false
            && isNaN(_extent[1]) == false
            && isNaN(_extent[2]) == false
            && isNaN(_extent[3]) == false
            ){
                 _bbox = "POLYGON("
                        + "(" + _extent[0] + " " + _extent[1]
                        + "," + _extent[0] + " " + _extent[3]
                        + "," + _extent[2] + " " + _extent[3]
                        + "," + _extent[2] + " " + _extent[1]
                        + "," + _extent[0] + " " + _extent[1]
                        + ")"
                        + ")"
                        ;
                 _bbox = {wkt: _bbox};
             
            }else{
            	_bbox = null;
            }
       }
         
       var _defer = $q.defer();
       _trackings = [];
       if(_element.tripId){
    	   for(_key in MonitoraggioTplSrv.trackings){
    		   if(_element.tripId == MonitoraggioTplSrv.trackings[_key].tripId){
    			   _trackings.push(MonitoraggioTplSrv.trackings[_key]);
    		   }
    	   }
       }else if(_element.routeId){
    	   for(_key in MonitoraggioTplSrv.trackings){
    		   if(_element.routeId == MonitoraggioTplSrv.trackings[_key].routeId){
    			   _trackings.push(MonitoraggioTplSrv.trackings[_key]);
    		   }
    	   }
       }else if(_element.agencyId){
    	   for(_key in MonitoraggioTplSrv.trackings){
    		   if(_element.agencyId == MonitoraggioTplSrv.trackings[_key].agencyId){
    			   _trackings.push(MonitoraggioTplSrv.trackings[_key]);
    		   }
    	   }
       }
       _tripToRemove = MonitoraggioTplSrv.tripToRemove[_element.agencyId];
       if(!_tripToRemove)
    	   _tripToRemove = [];
       _bbox = null;//Per off/on 
       var req = {method: 'POST'
                 ,url   : configuration.getParam("Constants").URL_RICERCA_MONITORAGGIO_FEATURE_MEZZI
                 ,data  : {ids       : [_element]
                          ,trackings : _trackings
                          ,bbox      : _bbox
                          ,notTripIds: _tripToRemove 
                          }
                 };
       $http(req).then(function(response     ){_defer.resolve(response);}
                      ,function(errorResponse){_defer.resolve(null);}
                      );
       
       return _defer.promise;
     };
     
     //Eventi su popup
      //Lista tab
     this.tabActive    = [];
     this.listaEventi  = [];
     this.listaAllarmi = [];
    //Init Tab
     this.initTab = function(_agencyId, _routeId, _tripId, _day){
          _key = _agencyId + ";" + _tripId + ";" + _routeId + ";" + _day;
          if(!this.tabActive[_key]){
              this.tabActive[_key] = 1;
              this.listaEventi = [];
              this.listaAllarmi = [];
          }
          return _key;
      };
      
    //Classe div tab del popup
      this.classDivPopup = function(_agencyId, _routeId, _tripId, _day, _index){
          _key = this.initTab(_agencyId, _routeId, _tripId, _day);
          return this.tabActive[_key] == _index ? 'tab-pane active' : 'tab-pane';
      };
    //Click un tab
      this.changeTabPopup = function(_agencyId, _routeId, _tripId, _vehicleId, _startDay, _endDay, _index){
          _key = this.initTab(_agencyId, _routeId, _tripId, _startDay);
          this.tabActive[_key] = _index;
      };
    //Classe li tab del popup
      this.classLiPopup = function(_agencyId, _routeId, _tripId, _day, _index){
          _key = this.initTab(_agencyId, _routeId, _tripId, _day);
          return this.tabActive[_key] == _index ? 'active' : '';
      };
      this.formatUtcByMessage = function(_utc){
          return DateService.formatUtcByMessage(_utc,'tpl.monitoraggio.popup.tab2.dateformat')
      };
    //Function per recupero lista eventi    
    this.listaEventiFunction = function(_agencyId, _routeId, _tripId, _day){
     var _defer = $q.defer();
     var req = {method: 'POST'
               ,url   : configuration.getParam("Constants").MONITORAGGIO_TPL_LISTA_EVENTI
               ,params: {"agencyId": _agencyId 
                        ,"routeId" : _routeId
                        ,"tripId"  : _tripId
                        ,"start"   : _day
                        }
               };
     $http(req).then(function(response     ){_defer.resolve(response);}
                    ,function(errorResponse){_defer.resolve(null);}
     );
     
     return _defer.promise;
    };
    
    //Function per add feature agency    
    this.listaAllarmiFunction = function(_agencyId, _routeId, _tripId, _vehicleId, _startDay, _endDay){
     var _defer = $q.defer();
     var req = {method: 'POST'
               ,url   : configuration.getParam("Constants").MONITORAGGIO_TPL_LISTA_ALLARMI
               ,params: {"agencyId" : _agencyId 
                        ,"routeId"  : _routeId
                        ,"tripId"   : _tripId
                        ,"vehicleId": _vehicleId
                        ,"start"    : _startDay
                        ,"end"      : _endDay
                        }
                };
     $http(req).then(function(response     ){_defer.resolve(response);}
                    ,function(errorResponse){_defer.resolve(null);}
                     );
     
     return _defer.promise;
    };
    
    this.checkAbilitaTracking = function(_idAgency, _idRoute, _idTrip, _startDay){
        _element = {agencyId: _idAgency
                   ,routeId : _idRoute
                   ,tripId  : _idTrip
                   ,startDay: _startDay
                    };
        _tracking = MonitoraggioTplSrv.trackings[MonitoraggioTplSrv.getKey(_element)];
        return !_tracking || _tracking == null || !_tracking.agencyId || _tracking.agencyId == null;
    };
    
    this.linear = function(event, id, codmez, trip, agency, route,_isSinottico){
    	if(!_isSinottico)
    		_isSinottico = false;
  	  event.preventDefault();
  	  var callbackdetach = function(){
  			var baseUrl = window.location.protocol + "//" + window.location.host + configuration.getParam("Constants").ContextPath; //TODO
  			var defUrl = baseUrl+ "monitoringTplCtrl/linear?st=true&page=monitoringTplCtrl/linear&id="+id+"&trip="+trip+"&agency="+agency+"&routeId="+route +"&isSinottico=" + _isSinottico;
  			var stile = "top=10, left=10, width=500, height=300, status=no, menubar=no, toolbar=no scrollbars=yes";
  			var w = window.open(decodeURIComponent(defUrl), "Linearizzata - "+codmez, stile);
  	  }
  	  readerMenu.openNewSingleWindow(event, "linear"+id,"Linearizzata - "+codmez,"monitoringTplCtrl/linear?id="+id+"&trip="+trip+"&agency="+agency+"&routeId="+route +"&isSinottico=" + _isSinottico,null,null,callbackdetach);
  	}
  	
    this.checkDisabilitaTracking = function(_idAgency, _idRoute, _idTrip, _startDay){
        return this.checkAbilitaTracking(_idAgency, _idRoute, _idTrip, _startDay) == false;
    };
    
    this.abilitaDisabilitaTracking = function(_idAgency, _idRoute, _idTrip, _startDay){
        _element = {agencyId: _idAgency
                   ,routeId : _idRoute
                   ,tripId  : _idTrip
                   ,startDay: _startDay
                   };
        _key = MonitoraggioTplSrv.getKey(_element);
        if(this.checkAbilitaTracking(_idAgency, _idRoute, _idTrip, _startDay)){
        	MonitoraggioTplSrv.trackings[_key] = _element;
        }else{
        	MonitoraggioTplSrv.trackings[_key] = {};
        }
    };
    
  //Aggiorna lista Eventi
    this.aggiornaListaEventi = function(_agencyId, _routeId, _tripId, _day, _index){
        this.listaEventi = [];
          var _defer = $q.defer();
          _promise = MonitoraggioTplSrv.listaEventiFunction(_agencyId, _routeId, _tripId, _day);
          _promise.then(function(response) {
                                              if(response.status = 200)
                                                  if(response.data.success){
                                                      this.listaEventi = response.data.aaData;
                                                  }
                                           _defer.resolve(1);
                                           }
                       ,function(response) {
                               _defer.reject({ msg : ""});
                               _defer.resolve(0);
                                          }
                       );
      };
      this.aggiornaListaAllarmi = function(_agencyId, _routeId, _tripId, _vehicleId, _startDay, _endDay){
          this.listaAllarmi = [];
          var _defer = $q.defer();
          _promise = MonitoraggioTplSrv.listaAllarmiFunction(_agencyId, _routeId, _tripId, _vehicleId, _startDay, _endDay);
          _promise.then(function(response) {
              if(response.status = 200)
                  if(response.data.success){
                      this.listaAllarmi = response.data.aaData;
                  }
              _defer.resolve(1);
          }
          ,function(response) {
              _defer.reject({ msg : ""});
              _defer.resolve(0);
          }
          );
      };
      
      
      /**************************************************************		EVENTO		*/
      var _layerEventi = configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_EVENTI"];
      MonitoraggioTplSrv.vectorEventi   = null;
      
      _sizeEvento = [30, 30];
      _imageEvento = olStyleService.createOlStyleIcon(configuration.getParam("Constants").ContextPath + "app/shared/layer_marker_icon/m_eventi_square.png", _sizeEvento);
      var _styleEvento = new ol.style.Style({image : _imageEvento ,zIndex: 2});
      
      MonitoraggioTplSrv.eventFeatureHide = [];
      MonitoraggioTplSrv.eventFeatureView = [];
      /****************************************/
      /** Aggiungi la feature dell'evento	 **/ 
      /****************************************/
      this.addEvento = function(_element, _olMap){
    	  console.log("MonitoraggioTplService		>>> Aggiungo l'EVENTO alla mappa");
		  var _defer = $q.defer();
		  _promise = this.monitoraEventi(_element);
		  this.addLayer(_promise, _styleEvento, _defer, _layerEventi, _element, false, false, true, false, false);
      };
      /****************************************/
      /** Remove la feature dell'evento	 	 **/ 
      /****************************************/
      this.removeEvento = function(_element, _olMap){
    	  log.debug("MonitoraggioTplService		>>> Inizio operazione per rimuovere feature EVENTO alla mappa");
    	  if(MonitoraggioTplSrv.olMap == null){
    		  MonitoraggioTplSrv.olMap = _olMap;
          }
    	  _featureElement = MonitoraggioTplSrv.eventFeatureView[_element.codiceEvento];
    	  /* Elimino la feature dalle FEATURE ATTIVE*/
		  if ( MonitoraggioTplSrv.eventFeatureView[_element.codiceEvento]!=undefined )
			  delete MonitoraggioTplSrv.eventFeatureView[_element.codiceEvento];
    	  /* Aggiungo la feature alle FEATURE NON ATTIVE */
		  MonitoraggioTplSrv.eventFeatureHide[_element.codiceEvento] = _featureElement;
		  /* Elimino la feature */
		  MonitoraggioTplSrv.vectorEventi.removeFeature(_featureElement);
      };
      /****************************************/
      /** Recupera le feature degli eventi	 **/ 
      /****************************************/    
      this.monitoraEventi = function(_element){
    	  log.debug("MonitoraggioTplService >>> Recupero della feature EVENTO");
    	  if(this.olMap && this.olMap.getView() && this.olMap.getSize()){
                _extent = ol.proj.transformExtent(this.olMap.getView().calculateExtent(this.olMap.getSize()),configuration.getParam("Constants").DEST_PROJECTION,configuration.getParam("Constants").SOURCE_PROJECTION);
                if(_extent != null && _extent.length == 4 && isNaN(_extent[0]) == false && isNaN(_extent[1]) == false && isNaN(_extent[2]) == false && isNaN(_extent[3]) == false ){
                	_bbox = "POLYGON("+ "(" + _extent[0] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[1]+ ")"+ ")";
                	_bbox = {wkt: _bbox};
                } else {
                	_bbox = null;
                }
    	  }
    	  /** Effettuo la chiamata per il recupero delle feature **/
    	  _searchModel = {};
  		  _searchModel.locale 			= _element.locale;
  		  _searchModel.codiceEvento 	= _element.codiceEvento;
		  _searchModel.iDisplayStart  	= 0
		  _searchModel.iDisplayLength 	= 1;
		  _searchModel.isEnd			= null;
		  _searchModel.noDate			= true;
  		  var _defer = $q.defer();
  		  var request = {
  				  method: 'POST',
  				  url: configuration.getParam("Constants").URL_FEATURE_EVENTI
  				  ,data  : _searchModel
  		  };
    	  $http(request).then(function(response){_defer.resolve(response);}, function(errorResponse){_defer.resolve(null);});
    	  return _defer.promise;
      };
      
      
      
      
      
      /**************************************************************		ANOMALIA		*/
      var _layerAnomalia = configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_ANOMALIE"];
      MonitoraggioTplSrv.vectorAnomalie   = null;
      
      _sizeAnomalia = [30, 30];
      _imageAnomalia = olStyleService.createOlStyleIcon(configuration.getParam("Constants").ContextPath + "app/shared/layer_marker_icon/m_warning.png", _sizeAnomalia);
      var _styleAnomalia = new ol.style.Style({image : _imageAnomalia ,zIndex: 2});
      
      MonitoraggioTplSrv.anomaliaFeatureHide = [];
      MonitoraggioTplSrv.anomaliaFeatureView = [];
      /****************************************/
      /** Aggiungi la feature dell'anomalia	 **/ 
      /****************************************/
      this.addAnomalia = function(_element, _olMap){
    	  log.debug("MonitoraggioTplService		>>> Aggiungo l'ANOMALIA alla mappa");
		  var _defer = $q.defer();
		  _promise = this.monitoraAnomalia(_element);
		  this.addLayer(_promise, _styleAnomalia, _defer, _layerAnomalia, _element, false, false, false, true, false);
      };
      /****************************************/
      /** Remove la feature dell'anomalia	 	 **/ 
      /****************************************/
      this.removeAnomalia = function(_element, _olMap){
    	  log.debug("MonitoraggioTplService		>>> Rimuovo l'anomalia alla mappa");
    	  if(MonitoraggioTplSrv.olMap == null){
    		  MonitoraggioTplSrv.olMap = _olMap;
          }
    	  _featureElement = MonitoraggioTplSrv.anomaliaFeatureView[_element.codiceAnomalia];
    	  /* Elimino la feature dalle FEATURE ATTIVE*/
		  if ( MonitoraggioTplSrv.anomaliaFeatureView[_element.codiceAnomalia]!=undefined )
			  delete MonitoraggioTplSrv.anomaliaFeatureView[_element.codiceAnomalia];
    	  /* Aggiungo la feature alle FEATURE NON ATTIVE */
		  MonitoraggioTplSrv.anomaliaFeatureHide[_element.codiceAnomalia] = _featureElement;
		  /* Elimino la feature */
		  MonitoraggioTplSrv.vectorAnomalie.removeFeature(_featureElement);
      };
      /****************************************/
      /** Recupera le feature delle anomalie **/ 
      /****************************************/    
      this.monitoraAnomalia = function(_element){
    	  log.debug("MonitoraggioTplService >>> Recupero della feature ANOMALIA");
    	  if(this.olMap && this.olMap.getView() && this.olMap.getSize()){
                _extent = ol.proj.transformExtent(this.olMap.getView().calculateExtent(this.olMap.getSize()),configuration.getParam("Constants").DEST_PROJECTION,configuration.getParam("Constants").SOURCE_PROJECTION);
                if(_extent != null && _extent.length == 4 && isNaN(_extent[0]) == false && isNaN(_extent[1]) == false && isNaN(_extent[2]) == false && isNaN(_extent[3]) == false ){
                	_bbox = "POLYGON("+ "(" + _extent[0] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[1]+ ")"+ ")";
                	_bbox = {wkt: _bbox};
                } else {
                	_bbox = null;
                }
    	  }
    	  /** Effettuo la chiamata per il recupero della feature **/
    	  _searchModel = {};
  		  _searchModel.locale 			= _element.locale;
  		  _searchModel.codiceAnomalia 	= _element.codiceAnomalia;
		  _searchModel.iDisplayStart  	= 0
		  _searchModel.iDisplayLength 	= 1;
  		  var _defer = $q.defer();
  		  var request = {
  				  method: 'POST',
  				  url: configuration.getParam("Constants").URL_FEATURE_ANOMALIE
  				  ,data  : _searchModel
  		  };
    	  $http(request).then(function(response){_defer.resolve(response);}, function(errorResponse){_defer.resolve(null);});
    	  return _defer.promise;
      };
      
      
      /**************************************************************		ALLARME		*/
      var _layerAllarme = configuration.getParam("Constants").layersName["MONITORAGGIO_TPL_ALLARME"];
      MonitoraggioTplSrv.vectorAllarme   = null;
      
      _sizeAllarme = [30, 30];
      _imageAllarme = olStyleService.createOlStyleIcon(configuration.getParam("Constants").ContextPath + "app/shared/layer_marker_icon/m_warning.png", _sizeAllarme);
      var _styleAllarme = new ol.style.Style({image : _imageAllarme ,zIndex: 2});
      
      MonitoraggioTplSrv.allarmeFeatureHide = [];
      MonitoraggioTplSrv.allarmeFeatureView = [];
      /****************************************/
      /** Aggiungi la feature dell'allarme	 **/ 
      /****************************************/
      this.addAllarme = function(_element, _olMap){
    	  log.debug("MonitoraggioTplService		>>> Aggiungo l'ALLARME alla mappa");
		  var _defer = $q.defer();
		  _promise = this.monitoraAllarme(_element);
		  this.addLayer(_promise, _styleAllarme, _defer, _layerAllarme, _element, false, false, false, false, true);
      };
      /****************************************/
      /** Remove la feature dell'allarme	 	 **/ 
      /****************************************/
      this.removeAllarme = function(_element, _olMap){
    	  log.debug("MonitoraggioTplService		>>> Rimuovo l'allarme dalla mappa");
    	  if(MonitoraggioTplSrv.olMap == null){
    		  MonitoraggioTplSrv.olMap = _olMap;
          }
    	  _featureElement = MonitoraggioTplSrv.allarmeFeatureView[_element.codiceAllarme];
    	  /* Elimino la feature dalle FEATURE ATTIVE*/
		  if ( MonitoraggioTplSrv.allarmeFeatureView[_element.codiceAllarme]!=undefined )
			  delete MonitoraggioTplSrv.allarmeFeatureView[_element.codiceAllarme];
    	  /* Aggiungo la feature alle FEATURE NON ATTIVE */
		  MonitoraggioTplSrv.allarmeFeatureHide[_element.codiceAllarme] = _featureElement;
		  /* Elimino la feature */
		  MonitoraggioTplSrv.vectorAllarme.removeFeature(_featureElement);
      };
      /****************************************/
      /** Recupera le feature degli allarmi **/ 
      /****************************************/    
      this.monitoraAllarme = function(_element){
    	  log.debug("MonitoraggioTplService >>> Recupero della feature ALLARME");
    	  if(this.olMap && this.olMap.getView() && this.olMap.getSize()){
                _extent = ol.proj.transformExtent(this.olMap.getView().calculateExtent(this.olMap.getSize()),configuration.getParam("Constants").DEST_PROJECTION,configuration.getParam("Constants").SOURCE_PROJECTION);
                if(_extent != null && _extent.length == 4 && isNaN(_extent[0]) == false && isNaN(_extent[1]) == false && isNaN(_extent[2]) == false && isNaN(_extent[3]) == false ){
                	_bbox = "POLYGON("+ "(" + _extent[0] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[3]+ "," + _extent[2] + " " + _extent[1]+ "," + _extent[0] + " " + _extent[1]+ ")"+ ")";
                	_bbox = {wkt: _bbox};
                } else {
                	_bbox = null;
                }
    	  }
    	  /** Effettuo la chiamata per il recupero della feature **/
    	  _searchModel = {};
  		  _searchModel.locale 			= _element.locale;
  		  _searchModel.codiceAllarme 	= _element.codiceAllarme;
		  _searchModel.iDisplayStart  	= 0
		  _searchModel.iDisplayLength 	= 1;
  		  var _defer = $q.defer();
  		  var request = {
  				  method: 'POST',
  				  url: configuration.getParam("Constants").URL_FEATURE_ALLARME
  				  ,data  : _searchModel
  		  };
    	  $http(request).then(function(response){_defer.resolve(response);}, function(errorResponse){_defer.resolve(null);});
    	  return _defer.promise;
      };
}]);